package topic;

import com.rabbitmq.client.*;
import util.Tools;

public class RecvLogsTopic2 {
    private static final String EXCHANGE_NAME = "topic_logs";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = Tools.getFactory();
        Connection connection = factory.newConnection();
        connection.createChannel();
        // 声明一个direct类型的交换机
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.TOPIC);
        // 声明一个随机临时队列，该队列会在使用完后自动销毁
        String queueName = channel.queueDeclare().getQueue();
        String routingKey1 = "*.*.rabbit";
        channel.queueBind(queueName, EXCHANGE_NAME, routingKey1);

        String routingKey2 = "lazy.#";
        channel.queueBind(queueName, EXCHANGE_NAME, routingKey2);

        System.out.println("开始接收消息");
        // 创建消费者
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            // 消息到达时会调用此方法
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) {
                String message = new String(body);
                System.out.println("接收消息，路由键为：'" + envelope.getRoutingKey() + "'，内容为：'" + message + "'");
            }
        };
        // 消费消息
        channel.basicConsume(queueName, true, consumer);
    }
}
